import type { Recordable, UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';

import {
  getAccessCodesApi,
  logoutApi,
  getOidcUserInfoApi,
  exchangeTokenApi,
  loginRedirectApi,
} from '#/api';
import { $t } from '#/locales';
import { authConfig } from '#/utils/daprplus';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  async function loginRedirect() {
    return loginRedirectApi();
  }

  async function handleOidcCallback(code: string) {
    try {
      // 获取存储的code_verifier
      const codeVerifier = sessionStorage.getItem('code_verifier');
      if (!codeVerifier) {
        throw new Error('No code verifier found');
      }

      // 请求token
      const tokenResponse = await exchangeTokenApi(code, codeVerifier);

      const { access_token, expires_in, refresh_token, id_token } =
        tokenResponse;

      if (!access_token || !id_token) {
        throw new Error('Invalid token response');
      }

      // 设置token相关信息
      accessStore.setAccessToken(access_token);
      accessStore.setAccessTokenExpiresIn(expires_in);

      // 存储refresh token
      if (refresh_token) {
        accessStore.setRefreshToken(refresh_token);
      }

      // 存储id_token并获取用户信息
      accessStore.setIdToken(id_token);

      const [userInfo] = await Promise.all([
        fetchUserInfo(),
        // getAccessCodesApi(),
      ]);

      if (!userInfo) {
        throw new Error('Failed to parse id_token');
      }

      userStore.setUserInfo(userInfo);
      // accessStore.setAccessCodes(accessCodes);

      if (userInfo.realName) {
        notification.success({
          description: `${$t('authentication.loginSuccessDesc')}:${userInfo.realName}`,
          duration: 3,
          message: $t('authentication.loginSuccess'),
        });
      }

      // 重定向到首页
      await router.push(userInfo.homePath || DEFAULT_HOME_PATH);
    } catch (error) {
      console.error(error);
      throw error;
    } finally {
      // 清除code_verifier
      sessionStorage.removeItem('code_verifier');
    }
  }

  async function logout() {
    const idToken = accessStore.idToken;
    await logoutApi(idToken);
  }

  async function logoutCallback() {
    resetAllStores();
    accessStore.setLoginExpired(false);
    await router.replace(LOGIN_PATH);
  }

  function parseIdToken(idToken: string): UserInfo | null {
    try {
      const [, payload] = idToken.split('.');
      if (!payload) {
        throw new Error('Invalid id_token format');
      }

      const decodedPayload = JSON.parse(atob(payload));
      const config = authConfig();

      // 验证颁发者
      if (decodedPayload.iss !== `${config.authority}/`) {
        throw new Error('Invalid token issuer');
      }

      // 验证受众
      if (decodedPayload.aud !== config.clientId) {
        throw new Error('Invalid token audience');
      }

      // 转换为UserInfo类型
      return {
        userId: decodedPayload.sub,
        username: decodedPayload.name,
        realName: decodedPayload.name,
        email: decodedPayload.email,
        phone_number: decodedPayload.phone_number,
        roles: ['user'], // 默认角色
        homePath: DEFAULT_HOME_PATH,
        avatar: '',
        desc: '', // 用户描述
        token: accessStore.accessToken || '',
      };
    } catch (e) {
      console.error('Failed to parse id_token:', e);
      return null;
    }
  }

  async function fetchUserInfo() {
    const idToken = accessStore.idToken;
    const currentAccessToken = accessStore.accessToken;

    if (!idToken || !currentAccessToken) {
      return null;
    }

    try {
      // 解析id_token获取基本信息
      const userInfo = parseIdToken(idToken);
      if (!userInfo) {
        throw new Error('Failed to parse id_token');
      }

      // 从userinfo endpoint获取完整用户信息
      const oidcUserInfo = await getOidcUserInfoApi();

      // 使用userinfo endpoint的信息更新用户信息
      userInfo.realName = oidcUserInfo.nickname || userInfo.realName;
      userInfo.avatar = oidcUserInfo.picture || userInfo.avatar;
      userInfo.email = oidcUserInfo.email || userInfo.email;
      userInfo.email_verified =
        oidcUserInfo.email_verified || userInfo.email_verified || false;
      userInfo.phone_number =
        oidcUserInfo.phone_number || userInfo.phone_number;
      userInfo.phone_number_verified =
        oidcUserInfo.phone_number_verified ||
        userInfo.phone_number_verified ||
        false;
      userInfo.roles = oidcUserInfo.role || userInfo.roles;

      userStore.setUserInfo(userInfo);
      return userInfo;
    } catch (e) {
      console.error('Failed to get user info:', e);
      return null;
    }
  }

  function $reset() {
    loginLoading.value = false;
  }

  return {
    $reset,
    loginRedirect,
    fetchUserInfo,
    loginLoading,
    logout,
    logoutCallback,
    handleOidcCallback,
  };
});
